import {
  Flex,
  FormControl,
  FormLabel,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Textarea,
  useToast,
} from '@chakra-ui/react';

import { useEffect, useRef, useState } from 'react';

import { useTranslation } from 'react-i18next';

import trainService from '@/api/train.service';
import IAIButton from '@/common/components/IAIButton';
import IAIInput from '@/common/components/IAIInput';

import { ModelTraining } from '@/pages/Training/Model';
type SettingsModalProps = {
  onEditClose: (info: Partial<ModelTraining>) => void;
  isEditOpen: boolean;
  model: ModelTraining | null;
};
interface EditForm {
  modelDesc: string;
  name: string;
  triggerWords: string;
}
const EditModal = ({ isEditOpen, model, onEditClose }: SettingsModalProps) => {
  const { name, modelDesc, triggerWords } = model ?? {};
  const { t } = useTranslation();
  const toast = useToast();
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [
    { modelDesc: _modelDesc, name: _name, triggerWords: _triggerWords },
    setForm,
  ] = useState<EditForm>({
    modelDesc: model?.modelDesc || '',
    name: model?.name || '',
    triggerWords: model?.triggerWords || '',
  });
  const initialRef = useRef(null);
  const finalRef = useRef(null);

  const handleSubmit = () => {
    if (!_name || !_triggerWords) {
      return toast({
        position: 'top',
        description: '请正确填写模型信息！',
        status: 'warning',
        duration: 3000,
        isClosable: true,
      });
    }
    setIsLoading(true);

    const params: Partial<ModelTraining> = {
      id: model?.id,
      modelDesc: _modelDesc,
      name: _name,
      triggerWords: _triggerWords,
    };

    trainService
      .updateModel(params)
      .then(({ code }) => {
        setIsLoading(false);
        if (code === 200) {
          onEditClose(params);
          toast({
            position: 'top',
            description: '模型信息已修改！',
            status: 'success',
            duration: 3000,
            isClosable: true,
          });
        }
      })
      .catch(() => {
        setIsLoading(false);
      });
  };

  useEffect(() => {
    setForm({
      modelDesc: modelDesc || '',
      name: name || '',
      triggerWords: triggerWords || '',
    });
  }, [name, modelDesc, triggerWords]);

  return (
    <Modal
      isOpen={isEditOpen}
      onClose={onEditClose}
      size="lg"
      isCentered
      initialFocusRef={initialRef}
      finalFocusRef={finalRef}
    >
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>{t('training.editModel')}</ModalHeader>
        <ModalCloseButton />
        <ModalBody>
          <Flex direction="column" gap="4">
            <IAIInput
              ref={initialRef}
              isRequired
              label="模型名称"
              placeholder="请填写模型名称"
              value={_name}
              onChange={(e) => {
                setForm(() => ({
                  name: e.target.value,
                  modelDesc,
                  triggerWords,
                }));
              }}
            ></IAIInput>
            <IAIInput
              isRequired
              label="模型调用触发词"
              placeholder="请填写触发词"
              value={_triggerWords}
              onChange={(e) => {
                setForm(() => ({
                  triggerWords: e.target.value,
                  modelDesc,
                  name,
                }));
              }}
            ></IAIInput>
            <FormControl>
              <FormLabel>模型描述</FormLabel>
              <Textarea
                onChange={(e) => {
                  setForm(() => ({
                    modelDesc: e.target.value,
                    triggerWords,
                    name,
                  }));
                }}
                value={_modelDesc}
                placeholder="请填写模型描述"
                fontSize="sm"
              />
            </FormControl>
          </Flex>
        </ModalBody>

        <ModalFooter>
          <IAIButton size="sm" onClick={onEditClose}>
            {t('common.close')}
          </IAIButton>
          <IAIButton
            size="sm"
            isLoading={isLoading}
            colorScheme="accent"
            onClick={handleSubmit}
            ml={3}
          >
            {t('training.editSubmit')}
          </IAIButton>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export default EditModal;
